package com.hanxiaozhang.threadbase1ndedition.no5juccommonclass;

import java.util.concurrent.Exchanger;

/**
 * 〈一句话功能简述〉<br>
 * 〈Exchanger 交换器〉
 * <p>
 * 概念：
 * 用于两个工作线程之间交换数据
 * <p>
 * 常用方法：
 * exchange(V x)：等待另一个线程到达这个交换点，然后将给定的对象传输给它，并接收它的对象。
 * exchange(V x, long timeout, TimeUnit unit)：指定超时时间
 *
 * @author hanxinghua
 * @create 2021/11/14
 * @since 1.0.0
 */
public class No6Exchanger {


    private static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {

        new Thread(() -> {
            String s = "THREAD-1的数据";
            try {
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "线程,交换得到" + s);

        }, "THREAD-1").start();

        new Thread(() -> {
            String s = "THREAD-2的数据";
            try {
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "线程,交换得到" + s);

        }, "THREAD-2").start();


    }
}
